<template>
    <div class="edu-page-warp">
        <div class="edu-page-title">
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane
                    label="填写章节样例（中文）"
                    name="first"
                ></el-tab-pane>
                <el-tab-pane
                    label="填写章节样例（英文）"
                    name="second"
                ></el-tab-pane>
            </el-tabs>
        </div>
        <div
            v-for="(item, index) in chapter.cultureSchemeDetailList"
            :key="index"
        >
            <template v-if="!item.isOldContent || 3 != item.contentType">
                <div class="edu-opertion-bar" style="margin-top: 8px;">
                    <div
                        v-show="topNavItems[0].active"
                        class="float-left"
                        style="margin-right:20px"
                    >
                        <span
                            style="line-height: 32px;"
                            v-bind:class="{
                                'new-record':
                                    inChange && item.changeStatus == 1,
                                'edit-record':
                                    inChange && item.changeStatus == 2,
                                'remove-record':
                                    inChange && item.changeStatus == 3
                            }"
                            >{{ item.name }}</span
                        >
                    </div>
                    <div
                        v-show="topNavItems[1].active"
                        class="float-left"
                        style="margin-right:20px"
                    >
                        <span
                            style="line-height: 32px;"
                            v-bind:class="{
                                'new-record':
                                    inChange && item.changeStatus == 1,
                                'edit-record':
                                    inChange && item.changeStatus == 2,
                                'remove-record':
                                    inChange && item.changeStatus == 3
                            }"
                            >{{ item.nameEn }}</span
                        >
                    </div>
                    <div
                        v-if="item.contentType == 1"
                        class="float-right"
                        style="margin-right:20px"
                    >
                        <el-button
                            v-if="!item.status && !isRead && dataType * 1 == 2"
                            type="text"
                            @click="handleCopyChapter(item)"
                            >复制之前</el-button
                        >
                        <el-button
                            v-if="!item.status && !isRead"
                            type="text"
                            @click="handleEditChapter(item)"
                            >{{ $t("common.btn.edit") }}</el-button
                        >
                    </div>
                    <div v-if="item.contentType == 2" class="float-right">
                        <el-button
                            type="text"
                            v-if="!isRead"
                            @click="relateTable(item)"
                            >{{ $t("culture.relationalSysTable") }}</el-button
                        >
                    </div>
                </div>
                <Tinymce
                    v-show="
                        item.status &&
                            item.contentType == 1 &&
                            topNavItems[0].active
                    "
                    ref="editor"
                    :height="200"
                    v-model="item.content"
                    :simple="false"
                    :toolbar="toolbar"
                    @editor-blur="handleSaveChapter(item)"
                />
                <Tinymce
                    v-show="
                        item.status &&
                            item.contentType == 1 &&
                            topNavItems[1].active
                    "
                    ref="editor"
                    :height="200"
                    :toolbar="toolbar"
                    v-model="item.contentEn"
                    :simple="false"
                    @editor-blur="handleSaveChapter(item)"
                />
                <div
                    v-show="
                        !item.status &&
                            item.contentType == 1 &&
                            topNavItems[0].active
                    "
                    class="conent-style"
                    v-html="item.content"
                ></div>
                <div
                    v-show="
                        !item.status &&
                            item.contentType == 1 &&
                            topNavItems[1].active
                    "
                    class="conent-style"
                    v-html="item.contentEn"
                ></div>
                <div
                    v-show="
                        !item.status &&
                            item.contentType == 2 &&
                            topNavItems[0].active
                    "
                    class=""
                >
                    <div v-if="item.detailTable">
                        <p v-html="item.detailTable.contentBefore"></p>
                        <template>
                            <courseCategoryForm
                                v-if="item.detailTable.table === 1"
                                :template-id="id"
                                :is-read="true"
                                :data-type="dataType"
                            />
                            <courseForm
                                v-else
                                :template-id="id"
                                :is-read="true"
                                :data-type="dataType"
                            />
                        </template>
                        <p v-html="item.detailTable.contentAfter"></p>
                    </div>
                </div>
                <div
                    v-show="
                        !item.status &&
                            item.contentType == 2 &&
                            topNavItems[1].active
                    "
                    class=""
                >
                    <div v-if="item.detailTable">
                        <p v-html="item.detailTable.contentBefore"></p>
                        <template>
                            <courseCategoryForm
                                v-if="item.detailTable.table === 1"
                                :template-id="id"
                                :is-read="true"
                                :data-type="dataType"
                            />
                            <courseForm
                                v-else
                                :template-id="id"
                                :is-read="true"
                                :data-type="dataType"
                            />
                        </template>
                        <p v-html="item.detailTable.contentAfter"></p>
                    </div>
                </div>
            </template>
        </div>
        <el-row class="pd-12px float-right" style="padding-right: 0;">
            <el-col :span="24">
                <el-button 
                size="medium" 
                @click="cancelChange"
                v-if="dataType != '1' && !isRead && status == 5"
                >取消变更</el-button>
                <el-button size="medium" @click="backStep">{{
                    $t("culture.scheme.prev")
                }}</el-button>
                <el-button size="medium" type="primary" @click="preview">{{
                    $t("common.btn.preview")
                }}</el-button>
                <el-button
                    size="medium"
                    @click="submitCheck"
                    v-if="dataType != '1' && !isRead"
                    >{{ $t("common.btn.submit") }}</el-button
                >
            </el-col>
        </el-row>

        <el-dialog
            :visible.sync="dialogVisible"
            :before-close="handleClose"
            :title="$t('culture.relationalTable')"
            width="60%"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-form
                ref="relateTableForm"
                :model="relateTableForm"
                label-position="left"
                label-width="80px"
                class="demo-ruleForm"
            >
                <el-form-item
                    :label="$t('culture.beforContent') + ':'"
                    prop="contentBefore"
                >
                    <Tinymce
                        v-if="!focusIndex"
                        ref="editor"
                        :height="100"
                        v-model="relateTableForm.contentBefore"
                        :simple="true"
                    />
                    <Tinymce
                        v-else
                        ref="editor"
                        :height="100"
                        v-model="relateTableForm.contentBeforeEn"
                        :simple="true"
                    />
                </el-form-item>
                <el-form-item
                    :label="$t('culture.relationalTable') + ':'"
                    prop="table"
                >
                    <el-radio-group
                        v-model="relateTableForm.table"
                        style="margin-bottom: 16px;"
                    >
                        <el-radio-button :label="1">{{
                            $t("culture.creditTable")
                        }}</el-radio-button>
                        <el-radio-button :label="2">{{
                            $t("culture.settingTable")
                        }}</el-radio-button>
                    </el-radio-group>
                    <courseCategoryForm
                        v-if="relateTableForm.table == 1"
                        :template-id="id"
                        :data-type="dataType"
                        :is-read="true"
                    />
                    <courseForm
                        v-if="relateTableForm.table == 2"
                        :template-id="id"
                        :data-type="dataType"
                        :is-read="true"
                    />
                </el-form-item>
                <el-form-item
                    :label="$t('culture.afterContent') + ':'"
                    prop="contentAfter"
                >
                    <Tinymce
                        v-if="!focusIndex"
                        ref="editor"
                        :height="100"
                        v-model="relateTableForm.contentAfter"
                        :simple="true"
                    />
                    <Tinymce
                        v-else
                        ref="editor"
                        :height="100"
                        v-model="relateTableForm.contentAfterEn"
                        :simple="true"
                    />
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">{{
                    $t("common.btn.cancel")
                }}</el-button>
                <el-button type="primary" @click="saveRelateTable">{{
                    $t("common.btn.confirm")
                }}</el-button>
            </span>
        </el-dialog>

        <el-dialog
            :visible.sync="copyVisible"
            title="复制之前"
            width="45%"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-form
                ref="copyForm"
                :model="copyForm"
                label-width="80px"
                label-position="left"
                class="pd-20px"
            >
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="年级:" prop="year">
                            <el-date-picker
                                v-model="copyForm.year"
                                value-format="yyyy"
                                type="year"
                                placeholder="选择学年"
                                style="width: 100%"
                                @change="handleChangYear"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="培养方案:" prop="schemeId">
                            <el-select
                                v-model="copyForm.schemeId"
                                style="width: 100%"
                                @change="handleChangScheme"
                            >
                                <el-option
                                    v-for="item in copyOptions.schemes"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="章节:" prop="chapterId">
                            <el-select
                                v-model="copyForm.chapterId"
                                style="width: 100%"
                                @change="handleChangChapter"
                            >
                                <el-option
                                    v-for="item in copyOptions.chapters"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer">
                <div>
                    <el-button @click="copyVisible = false">{{
                        $t("message.cancel")
                    }}</el-button>
                    <el-button type="primary" @click="handleSubmitCopy">{{
                        $t("message.confirm")
                    }}</el-button>
                </div>
            </span>
        </el-dialog>
        <schemeCheck
            :show="checkVisible"
            :id="id"
            :random-id="randomId"
            type="11"
            v-if="'1' !== dataType"
        />
    </div>
</template>

<script>
import {
    updateSchemeChapters,
    checkCultScheDetail,
    getTableId,
    findCultureSchemeListByYear,
    getSchemeChapters,
    findCultureScheDetailList,
    cancelChangeCultureScheme,
    findCultureSchemeById
} from "common/src/api/culture/bachelor";
import UTILS from "common/src/utils/utils";
import courseCategoryForm from "./courseCategoryForm";
import Tinymce from "common/src/components/tinymce";
import courseForm from "./courseForm";
import schemeCheck from "./schemeCheck";
import Bus from "common/src/utils/bus";

export default {
    name: "scheme-chapter",
    components: {
        Tinymce,
        courseCategoryForm,
        courseForm,
        schemeCheck
    },
    props: {
        type: {
            type: Boolean,
            default: false
        },
        next: {
            type: Function,
            default: null
        },
        dataType: {
            type: String,
            default: "1" // 1为模板，2为方案
        },
        templateId: {
            type: String,
            default: null // 当前方案Id
        },
        templateIdOrigin: {
            type: String,
            default: null // 当前模板Id
        },
        projId: {
            type: String,
            default: "1"
        },
        inChange: {
            type: Boolean,
            default: false
        },
        isRead: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            focusIndex: 0,
            checkVisible: false,
            id: "",
            dialogVisible: false,
            activeName: "first",
            topNavItems: [
                {
                    index: 0,
                    active: true
                },
                {
                    index: 1,
                    active: false
                }
            ],
            chapters: [],
            chapterIds: [],
            chapter: {
                type: this.dataType,
                cultureId: "",
                templateId: "",
                detailLanguage: "cn",
                cultureSchemeDetailList: []
            },
            relateTableForm: {
                id: "",
                contentBefore: "",
                contentBeforeEn: "",
                table: 1,
                contentAfter: "",
                contentAfterEn: ""
            },
            content: "",
            copyVisible: false,
            copyForm: {
                year: "",
                schemeId: "",
                chapterId: ""
            },
            copyOptions: {
                schemes: [],
                chapters: []
            },
            copyFormRules: {
                year: [
                    {
                        required: true,
                        message: "请输入年纪",
                        trigger: "change"
                    }
                ]
            },
            selectChapter: "",
            copyChapter: "",
            currentSchemeId: "",
            randomId: "",
            interval: null,
            intervalList: [],
            relateTableFormId: "",
            status: "",
            toolbar: [
                "insertfile undo redo | styleselect fontselect fontsizeselect| bold italic underline strikethrough …emoveformat subscript superscript | hr bullist numlist link image  preview anch…ia table emoticons forecolor backcolor fullscreen charmap"
            ]
        };
    },
    created() {
        if (this.dataType * 1 === 2) {
            this.id = this.$route.query.id;
        } else {
            this.id = this.templateId; //* 如果是模板章节id为模板id
        }
        this.init();

        // 接受选择课程的信息
        this.randomId = "dialogEvent" + new Date().getTime();
        Bus.$on(this.randomId, state => {
            this.checkVisible = state;
        });
        this.status = this.$route.query.status;
        this.getSchemeInfo && this.getSchemeInfo();
    },
    destroyed() {
        clearInterval(this.interval);
    },
    methods: {
        cancelChange(){
            cancelChangeCultureScheme(this.templateId).then(res => {
                if (res && res.code == 200) {
                    this.$message({
                        message: '操作成功！',
                        type: 'success'
                    })
                    this.$router.push({
                        name: "bclCultureSchemeManage"
                    });
                }
            });
        },
        autoSave(on) {
            if (on) {
                this.intervalList.push(1);
            } else {
                this.intervalList.pop();
            }
            if (!this.interval) {
                this.interval = setInterval(() => {
                    this.submit();
                }, 30000);
            } else {
                if (0 >= this.intervalList.length) {
                    clearInterval(this.interval);
                }
            }
        },
        init() {
            const obj = this.type
                ? {
                      type: 1
                  }
                : {};
            getSchemeChapters(
                Object.assign(
                    {
                        templateId: this.templateId,
                        cultureId:
                            this.dataType === 2 ? this.$route.query.id : ""
                    },
                    obj
                )
            ).then(res => {
                if (res && res.code === 200) {
                    this.chapter.cultureSchemeDetailList = res.data;
                    _.forEach(this.chapter.cultureSchemeDetailList, function(
                        item,
                        key
                    ) {
                        if (!item.content) {
                            item.content = "";
                        }
                        if (3 == item.contentType) {
                            item.isOldContent = true;
                        }
                        Vue.set(item, "status", false);
                        item.name =
                            UTILS.numberToChinese(key + 1) + "、" + item.name;
                        item.nameEn = key + 1 + "." + item.nameEn;
                    });
                }
            });
        },
        clickItem(item) {
            this.topNavItems.forEach(nav => {
                nav.active = false;
            });
            item.active = true;
            this.focusIndex = item.index;
        },
        handleClick(tab) {
            this.topNavItems.forEach(nav => {
                nav.active = false;
            });
            this.topNavItems.forEach(nav => {
                if (nav.index == tab.index) {
                    nav.active = true;
                    this.focusIndex = nav.index;
                }
            });
        },
        submit(callback) {
            this.chapter.templateId = this.templateId;
            if (this.dataType === 2) {
                this.chapter.cultureId = this.$route.query.id;
            }
            updateSchemeChapters(this.chapter).then(res => {
                if (res && res.code === 200) {
                    this.$notify.success({
                        title: "成功",
                        message: "章节保存成功！"
                    });

                    if (_.isFunction(callback)) {
                        callback();
                    }
                    if (callback == "table") {
                        this.resetObj();
                    }
                }
            });
        },
        submitCheck() {
            checkCultScheDetail({
                cultureId: this.id
            }).then(res => {
                if (res && res.code === 200) {
                    this.checkVisible = true;
                }
            });
        },
        // relateTable(item) {
        //     if (_.indexOf(this.chapterIds, item.id) === -1) {
        //         this.chapterIds.push(item.id);
        //     }

        //     this.chapter.cultureId = this.$route.query.id;
        //     const param = {
        //         chapterId: item.id,
        //         schemeId:
        //             this.dataType === 2
        //                 ? this.chapter.cultureId
        //                 : this.templateId,
        //         table: 1,
        //         type: this.dataType
        //     };
        //     getTableId(param).then(res => {
        //         if (res && res.code === 200) {
        //             this.relateTableForm = res.data;
        //         }
        //         this.dialogVisible = true;
        //     });
        // },
        relateTable(item) {
            if (_.indexOf(this.chapterIds, item.id) === -1) {
                this.chapterIds.push(item.id);
            }

            this.chapter.cultureId = this.$route.query.id;
            const param = {
                chapterId: item.id,
                schemeId:
                    this.dataType === 2
                        ? this.chapter.cultureId
                        : this.templateId,
                table: 1,
                type: this.dataType
            };
            getTableId(param).then(res => {
                if (res && res.code === 200) {
                    this.relateTableForm = res.data;
                }
                this.relateTableFormId = item.id;
                this.dialogVisible = true;
            });
        },
        // saveRelateTable() {
        //     const self = this;
        //     if (this.chapterIds.length === 0) return;
        //     _.forEach(this.chapterIds, function(val) {
        //         const item = _.findIndex(self.chapter.cultureSchemeDetailList, {
        //             id: val
        //         });
        //         if (!self.chapter.cultureSchemeDetailList[item].contentId) {
        //             self.chapter.cultureSchemeDetailList[item].contentId =
        //                 self.relateTableForm.id;
        //         }
        //         self.chapter.cultureSchemeDetailList[
        //             item
        //         ].detailTable = _.clone(self.relateTableForm);
        //     });

        //     _.forEach(self.relateTableForm, (val, key) => {
        //         self.relateTableForm[key] = "";
        //     });
        //     this.dialogVisible = false;
        //     this.submit();
        // },
        saveRelateTable() {
            const that = this;
            if (this.chapterIds.length === 0) return;
            // that.chapter.cultureSchemeDetailList.forEach(d =>{
            //     if(d.id == that.relateTableFormId){
            //         d.detailTable = that.relateTableForm
            //     }
            // })
            that.chapter.cultureSchemeDetailList.forEach(d => {
                if (d.id == that.relateTableFormId) {
                    d.detailTable = that.relateTableForm;
                    if (!d.contentId) {
                        d.contentId = that.relateTableForm.id;
                    }
                }
            });
            this.dialogVisible = false;
            let callback = "table";
            this.submit(callback);
            this.dialogVisible = false;
            this.resetObj();
        },
        resetObj() {
            this.relateTableForm = {
                id: "",
                contentBefore: "",
                contentBeforeEn: "",
                table: 1,
                contentAfter: "",
                contentAfterEn: ""
            };
            this.relateTableFormId = "";
        },
        handleEditChapter(item) {
            item.status = true;
            if (this.inChange) item.changeStatus = "2";
            this.autoSave(true);
        },
        handleSaveChapter(item) {
            this.autoSave(false);
            this.submit(function() {
                item.status = false;
            });
        },
        handleCopyChapter(item) {
            this.copyVisible = true;
            this.selectChapter = item;
        },
        handleChangChapter(val) {
            const param = {
                schemeId: this.currentSchemeId,
                chapterId: val
            };
            findCultureScheDetailList(param).then(res => {
                if (res && res.code === 200) {
                    this.copyChapter = res.data[0];
                }
            });
        },
        // 根据年级获取培养方案
        handleChangYear(val) {
            if (!val) return;
            const self = this;
            const param = {
                id: this.templateId,
                templateId: this.templateId,
                grade: this.copyForm.year
            };
            self.copyForm.schemeId = "";
            self.copyForm.chapterId = "";
            self.copyOptions.schemes = [];
            self.copyOptions.chapters =[];
            findCultureSchemeListByYear(param).then(res => {
                if (res && res.code === 200) {
                    _.forEach(res.data, item => {
                        self.copyOptions.schemes.push({
                            label: item.name,
                            value: item.id
                        });
                    });
                }
            });
        },
        handleChangScheme(val) {
            const self = this;
            const param = {
                schemeId: val,
                chapterId: ""
            };
            this.currentSchemeId = val;
            this.copyOptions.chapters.length = 0;
            self.copyForm.chapterId = "";
            self.copyOptions.chapters =[];
            findCultureScheDetailList(param).then(res => {
                if (res && res.code === 200) {
                    _.forEach(res.data, item => {
                        self.copyOptions.chapters.push({
                            label: item.name,
                            value: item.id
                        });
                    });
                }
            });
        },
        handleSubmitCopy() {
            const index = _.findIndex(
                this.chapter.cultureSchemeDetailList,
                this.selectChapter
            );
            if (this.copyChapter) {
                Vue.set(
                    this.chapter.cultureSchemeDetailList[index],
                    "content",
                    this.copyChapter.content
                );
                Vue.set(
                    this.chapter.cultureSchemeDetailList[index],
                    "contentEn",
                    this.copyChapter.contentEn
                );
            }
            this.copyVisible = false;
            this.submit();
        },
        // 上一步
        backStep() {
            if (this.next) {
                this.next(-1);
            }
        },
        // 预览模板
        // preview() {
        //     let routerName = "cultureTemplateView";
        //     this.$router.push({
        //         path: routerName,
        //         query: {
        //             projId: this.projId,
        //             id: this.id,
        //             templateId: this.templateIdOrigin,
        //             dataType: this.dataType,
        //             isRead: this.isRead,
        //             // templateIdOrigin: this.templateIdOrigin
        //         }
        //     });
        // },
        preview() {
            let routerName = "/bclCultureTemplateView";
            this.$router.push({
                path: routerName,
                query: {
                    projId: this.projId,
                    id: this.id,
                    templateId: this.templateIdOrigin,
                    dataType: this.dataType,
                    isRead: this.isRead
                    // templateIdOrigin: this.templateIdOrigin
                }
            });
        },
        // 下一步
        nextStep() {
            this.submit(() => {
                if (this.next) {
                    this.next();
                }
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.edu-page-title {
    span {
        cursor: pointer;
        display: inline-block;
        padding-right: 10px;
    }
    span.active {
        color: #2876c2;
    }
}

.conent-style {
    padding: 24px;
    border: 1px solid #dadcde;
}

.border-right {
    margin-right: 10px;
}
</style>
